package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Question;
import cn.wolfcode.luowowo.article.domain.WendaAnswer;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IQuestionService;
import cn.wolfcode.luowowo.article.service.IQuestionTagService;
import cn.wolfcode.luowowo.article.service.IWendaAnswerService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IUserInfoStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.UserInfoStats;
import cn.wolfcode.luowowo.common.query.WendaAnswerQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("question")
public class QuestionController {

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IQuestionService questionService;
    @Reference
    private IQuestionTagService tagService;

    @Reference
    private IWendaAnswerService wendaAnswerService;
    @Reference
    private IUserInfoStatsCacheService userInfoStatsCacheService;

    //问题
    @RequestMapping("wenda")
    public String wenda(WendaAnswerQueryObject qo, Model model) {
        List<Question> list = questionService.queryAll();//查询所有问题
        model.addAttribute("problems", list);
        //vo 回答数排行榜
        //查询redis中存储的zset数据,key为"answer_zset_sort",
        List<UserInfoStats> uis = userInfoStatsCacheService.listRankTOP10(RedisKey.ANSWER_ZSET_SORT);
        model.addAttribute("uis", uis);

        return "question/wenda";
    }

    //回答
    @RequestMapping("wendaDetail")
    public String detail(Long id, Model model) {
        Question question = questionService.queryById(id); //当前问题
        model.addAttribute("question", question);

        return "question/wendaDetail";
    }

    @RequiredLogin
    @RequestMapping("saveAnswer")
    @ResponseBody
    public AjaxResult wendaDetail(WendaAnswer answer, @LoginUser UserInfo user, Model model) {
        answer.setUser(user);
        answer.setAnswerTime(new Date());
        wendaAnswerService.save(answer);

        //回答一次,当前用户回答数+1.
        userInfoStatsCacheService.incr(user.getId(), 1, IUserInfoStatsCacheService.ANSWER_TYPE);

        //更新排行榜
        userInfoStatsCacheService.addRank(RedisKey.ANSWER_ZSET_SORT, 1, user.getId());

        //此问题的回答数加1
        questionService.incrAnswernum(answer.getQuestion().getId());
        return new AjaxResult();
    }


    @RequestMapping("")
    public String index(Model model) {
        //只要层级前3的目的地给前台
        model.addAttribute("dests", destinationService.getDestByDeep(3));
        return "question/public";
    }


    //问题保存
    @RequiredLogin
    @RequestMapping("save")
    @ResponseBody
    public Object save(Question content, @LoginUser UserInfo user) {
        if (user.getId() == null) {
            return new AjaxResult("先登录后回复", AjaxResult.NO_LOGIN_CODE);
        }
        return questionService.saveOrUpdate(content, user);
    }


    @Value("${file.dir}")
    private String fileDir;

    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic) {
        String upload = UploadUtil.upload(pic, fileDir);
        return upload;
    }



    @RequestMapping("updateStatus")
    @ResponseBody
    public Object updateStatus(Long id,int status,Model model) {
        questionService.updateStatus(id,status);
        return new AjaxResult();
    }

    //内容图片上传
    //UME上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        java.lang.String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, fileDir);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

}
